package com.attendance.chdingtask.service;

import com.attendance.chdingtask.dao.BaseJPA;
import com.attendance.chdingtask.dao.MdAreaDao;
import com.attendance.chdingtask.model.*;
import com.attendance.chdingtask.utils.common.Page;
import com.attendance.chdingtask.utils.excel.ExcelUtil;
import com.querydsl.jpa.impl.JPAQuery;
import com.querydsl.jpa.impl.JPAQueryFactory;
import org.apache.poi.hssf.usermodel.*;
import org.apache.poi.ss.usermodel.CellStyle;
import org.apache.poi.ss.util.CellRangeAddress;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletResponse;
import java.io.OutputStream;
import java.nio.charset.StandardCharsets;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;

@Service
public class MdAreaService extends BaseService<MdArea,Long>{

    private static final Logger logger= LoggerFactory.getLogger(MdAreaService.class);

    @Autowired
    private JPAQueryFactory queryDslTool;

    @Autowired
    private MdDetailsService detailsService;

    @Autowired
    private MdDeviceService deviceService;

    @Autowired
    private MdAreaDao dao;

    @Override
    protected BaseJPA<MdArea> getDao() {
        return dao;
    }

    public void findAreaByData(UserQryParm vo, Page<MdArea> page, String corpId) {
        List<MdArea> list=findUserByData(vo);
        if(null != list&& list.size()>0){
            for(MdArea area:list){
                Integer enterNum=0;
                Integer outNum=0;
                List<MdDevice> devices=deviceService.findByAreaId(area.getId(),corpId);
                for(MdDevice device:devices){
                    List<MdDetails> details= detailsService.findDataByDeviceId(vo,device.getId(),corpId);
                    if("J".equals(device.getFlag())){
                        enterNum=enterNum+details.size();
                    }else {
                        outNum=outNum+details.size();
                    }
                    device.setCountNum(details.size());
                }
                area.setDeviceList(devices);
                area.setEnterCount(enterNum);
                area.setOutCount(outNum);
                area.setResidueCount(enterNum-outNum);
            }
        }
        page.setList(list);
        page.setTotal(Long.valueOf(list.size()));

    }

    public List<MdArea> findUserByData(UserQryParm vo) {
        QMdArea qMdArea=QMdArea.mdArea;
        JPAQuery<MdArea> jpaQuery=queryDslTool.select(qMdArea).from(qMdArea);
        if(!isEmpty(vo.getUserName())){
            jpaQuery.where(qMdArea.areaType.eq(vo.getAreaType()));
        }
        if(null != vo.getAreaName()){
            jpaQuery.where(qMdArea.areaName.eq(vo.getAreaName()));
        }
        Page<MdArea> page=new Page<>();
        page.setPageCurrent(vo.getOffset());
        page.setPageSize(vo.getLimit());
        List<MdArea> list=jpaQuery.offset((page.getPageCurrent()-1)*page.getPageSize())
                .limit(page.getPageSize())
                .fetch();
        return list;
    }

    public void exportData(HttpServletResponse response, UserQryParm vo) throws Exception {
        OutputStream outputStream = response.getOutputStream();
        HSSFWorkbook wb = new HSSFWorkbook();
        List<MdArea> list=dao.findAll();
        Map<Long ,List<MdDetails>> map=new HashMap<>();

        if(null != list&& list.size()>0){
            for(MdArea area:list){
                Integer enterNum=0;
                Integer outNum=0;
                List<MdDevice> devices=deviceService.findByAreaIds(area.getId());
                for(MdDevice device:devices){
                    List<MdDetails> details= detailsService.findDataByDeviceIds(vo,device.getId());
                    if("J".equals(device.getFlag())){
                        enterNum=enterNum+details.size();
                    }else {
                        outNum=outNum+details.size();
                    }
                    device.setCountNum(details.size());
                    map.put(device.getId(),details);
                }
                area.setDeviceList(devices);
                area.setEnterCount(enterNum);
                area.setOutCount(outNum);
                area.setResidueCount(enterNum-outNum);
            }
        }

        HSSFSheet sheet=wb.createSheet("统计报表");
        sheet.autoSizeColumn(1,true);
        sheet.setDefaultColumnWidth(12);
        sheet.setDefaultRowHeight((short)(15*20));

        HSSFRow row=sheet.createRow(0);

        row.setHeightInPoints(20);
        HSSFCellStyle titleStyle=wb.createCellStyle();
        titleStyle.setAlignment(HSSFCellStyle.ALIGN_LEFT);

        HSSFCellStyle rowStyle = wb.createCellStyle();
        rowStyle.setAlignment(HSSFCellStyle.ALIGN_CENTER); // 创建一个居中格式
        //声明列对象
        HSSFCell cellTitle;
        cellTitle = row.createCell(0);
        cellTitle.setCellValue("Personal Details");
        cellTitle.setCellStyle(titleStyle);
        row = sheet.createRow(1);
        HSSFCell cellContent;
        cellContent = row.createCell(0);
        cellContent.setCellValue("设备地点");
        cellContent.setCellStyle(rowStyle);
        cellContent = row.createCell(1);
        cellContent.setCellValue("进入人数");
        cellContent.setCellStyle(rowStyle);
        cellContent = row.createCell(2);
        cellContent.setCellValue("出去人数");
        cellContent.setCellStyle(rowStyle);
        cellContent = row.createCell(3);
        cellContent.setCellValue("剩余人数");
        cellContent.setCellStyle(rowStyle);
        cellContent = row.createCell(4);
        cellContent.setCellValue("入口设备");
        cellContent.setCellStyle(rowStyle);
        cellContent = row.createCell(5);
        cellContent.setCellValue("识别人数");
        cellContent.setCellStyle(rowStyle);
        cellContent = row.createCell(6);
        cellContent.setCellValue("姓名");
        cellContent.setCellStyle(rowStyle);

        cellContent = row.createCell(7);
        cellContent.setCellValue("部门");
        cellContent.setCellStyle(rowStyle);

        cellContent = row.createCell(8);
        cellContent.setCellValue("扫码时间");
        cellContent.setCellStyle(rowStyle);

        cellContent = row.createCell(9);
        cellContent.setCellValue("扫码日期");
        cellContent.setCellStyle(rowStyle);

        cellContent = row.createCell(10);
        cellContent.setCellValue("扫码时间点");
        cellContent.setCellStyle(rowStyle);

        cellContent = row.createCell(11);
        cellContent.setCellValue("通行标签");
        cellContent.setCellStyle(rowStyle);

        cellContent = row.createCell(12);
        cellContent.setCellValue("识别类别");
        cellContent.setCellStyle(rowStyle);
        int rows=0;
        int i_FirstRow=2;
        int i_LastRow=0;
        for (int i = 0; i < list.size(); i++) {
            MdArea area=list.get(i);
            int enyerCount=area.getEnterCount();
            int outCount=area.getOutCount();
            int residueCount=area.getResidueCount();
            List<MdDevice> devices=area.getDeviceList();
            for(MdDevice device:devices){
                int countNum=device.getCountNum();
                List<MdDetails> details=map.get(device.getId());
                for(MdDetails mdDetails:details){
                    row = sheet.createRow(2 + rows);
                    cellContent = row.createCell(0);
                    cellContent.setCellValue(mdDetails.getAreaName());
                    cellContent.setCellStyle(rowStyle);
                    cellContent = row.createCell(1);
                    cellContent.setCellValue(enyerCount);
                    cellContent.setCellStyle(rowStyle);
                    cellContent = row.createCell(2);
                    cellContent.setCellValue(outCount);
                    cellContent.setCellStyle(rowStyle);
                    cellContent = row.createCell(3);
                    cellContent.setCellValue(residueCount);
                    cellContent.setCellStyle(rowStyle);
                    cellContent = row.createCell(4);
                    cellContent.setCellValue(mdDetails.getDeviceName());
                    cellContent.setCellStyle(rowStyle);
                    cellContent = row.createCell(5);
                    cellContent.setCellValue(countNum);
                    cellContent.setCellStyle(rowStyle);
                    cellContent = row.createCell(6);
                    cellContent.setCellValue(mdDetails.getUserName());
                    cellContent.setCellStyle(rowStyle);
                    cellContent = row.createCell(7);
                    cellContent.setCellValue(mdDetails.getDeptName());
                    cellContent.setCellStyle(rowStyle);
                    cellContent = row.createCell(8);
                    cellContent.setCellValue(mdDetails.getRecognizeTime());
                    cellContent.setCellStyle(rowStyle);
                    cellContent = row.createCell(9);
                    cellContent.setCellValue(mdDetails.getMdDate());
                    cellContent.setCellStyle(rowStyle);
                    cellContent = row.createCell(10);
                    cellContent.setCellValue(mdDetails.getMdTime());
                    cellContent.setCellStyle(rowStyle);
                    cellContent = row.createCell(11);
                    cellContent.setCellValue("成员");
                    cellContent.setCellStyle(rowStyle);
                    cellContent = row.createCell(12);
                    cellContent.setCellValue("人脸");
                    cellContent.setCellStyle(rowStyle);
                    rows++;
                }
                i_LastRow=i_LastRow+rows;
                if(i_LastRow>i_FirstRow){
                    CellRangeAddress v_CellRA = new CellRangeAddress(i_FirstRow
                            ,i_LastRow
                            ,5
                            ,6);
                    sheet.addMergedRegion(v_CellRA);
                    i_FirstRow=i_FirstRow+rows;
                }
            }
            if(i_LastRow>i_FirstRow){
                CellRangeAddress v_CellRA = new CellRangeAddress(i_FirstRow
                        ,i_LastRow
                        ,0
                        ,4);
                sheet.addMergedRegion(v_CellRA);
            }
        }
        wb.write(outputStream);
        //响应到客户端
        try (OutputStream os = response.getOutputStream()) {
            setResponseHeader(response,"入井登记管理平台报表.xlsx");
            wb.write(os);
            os.flush();
        } catch (Exception e) {
            logger.error(e.getMessage());
        }
    }

    //发送响应流方法
    public void setResponseHeader(HttpServletResponse response, String fileName) {
        try {
            fileName = new String(fileName.getBytes(), StandardCharsets.ISO_8859_1);
            response.setContentType("application/octet-stream;charset=ISO8859-1");
            response.setHeader("Content-Disposition", "attachment;filename=" + fileName);
            response.addHeader("Pargam", "no-cache");
            response.addHeader("Cache-Control", "no-cache");
        } catch (Exception e) {
            logger.error(e.getMessage());
        }
    }
}
